<template>
  <div class="main-layout h-screen flex flex-col bg-gray-50">
    <!-- 顶部栏 (隐藏) -->
    <div v-if="appStore.layout.showTopBar" class="top-bar">
      <div class="toolbar">
        <div class="flex items-center space-x-4">
          <h1 class="text-lg font-semibold">Database Manager</h1>
        </div>
        <div class="flex items-center space-x-2">
          <el-button 
            link 
            @click="appStore.toggleTheme"
            class="text-white hover:bg-white/10"
          >
            <el-icon><Sunny v-if="appStore.isDarkTheme" /><Moon v-else /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content flex-1 flex overflow-hidden">
      <!-- 侧边栏 -->
      <div 
        v-if="appStore.layout.showSidebar"
        class="sidebar flex-shrink-0 transition-all duration-300"
        :style="{ width: appStore.actualSidebarWidth + 'px' }"
      >
        <ServiceSidebar />
      </div>

      <!-- 内容区域 -->
      <div class="content-wrapper flex-1 flex flex-col overflow-hidden">
        <router-view />
      </div>
    </div>

    <!-- 状态栏 -->
    <div v-if="appStore.layout.showStatusBar" class="status-bar">
      <StatusBar />
    </div>

    <!-- 全局加载遮罩 -->
    <div v-if="appStore.loading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p class="mt-2 text-gray-600">加载中...</p>
      </div>
    </div>

    <!-- 全局消息提示 -->
    <div class="message-container">
      <transition-group name="message" tag="div">
        <div
          v-for="message in appStore.messages"
          :key="message.id"
          :class="[
            'message-item',
            `message-${message.type || 'info'}`
          ]"
        >
          <el-icon class="message-icon">
            <SuccessFilled v-if="message.type === 'success'" />
            <WarningFilled v-else-if="message.type === 'warning'" />
            <CircleCloseFilled v-else-if="message.type === 'error'" />
            <InfoFilled v-else />
          </el-icon>
          <span class="message-text">{{ message.text }}</span>
          <el-button
            link
            size="small"
            @click="appStore.removeMessage(message.id)"
            class="message-close"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </transition-group>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { useAppStore, useConnectionStore, useDatabaseStore, useTabStore } from '@/stores'
import ServiceSidebar from '@/components/layout/ServiceSidebar.vue'
import StatusBar from '@/components/layout/StatusBar.vue'

const appStore = useAppStore()
const connectionStore = useConnectionStore()
const databaseStore = useDatabaseStore()
const tabStore = useTabStore()

// 初始化应用
onMounted(async () => {
  // 恢复应用状态
  appStore.restoreState()
  
  // 加载连接配置
  try {
    await connectionStore.loadConnections()
  } catch (error) {
    console.error('Failed to load connections:', error)
    appStore.addMessage({
      type: 'error',
      text: '加载连接配置失败: ' + error.message
    })
  }
  
  // 加载支持的数据库类型
  try {
    await databaseStore.loadSupportedTypes()
  } catch (error) {
    console.error('Failed to load supported types:', error)
  }
  
  // 恢复查询历史
  databaseStore.restoreQueryHistory()
  
  // 监听窗口关闭事件
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // 监听键盘快捷键
  window.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
  window.removeEventListener('keydown', handleKeydown)
})

// 处理窗口关闭前事件
const handleBeforeUnload = (event) => {
  if (appStore.settings.confirmBeforeClose && tabStore.hasUnsavedTabs) {
    event.preventDefault()
    event.returnValue = '您有未保存的更改，确定要离开吗？'
    return event.returnValue
  }
}

// 处理键盘快捷键
const handleKeydown = (event) => {
  // Ctrl/Cmd + T: 新建查询标签页
  if ((event.ctrlKey || event.metaKey) && event.key === 't') {
    event.preventDefault()
    if (connectionStore.activeConnectionId) {
      tabStore.createQueryTab(connectionStore.activeConnectionId)
    }
  }
  
  // Ctrl/Cmd + W: 关闭当前标签页
  if ((event.ctrlKey || event.metaKey) && event.key === 'w') {
    event.preventDefault()
    if (tabStore.activeTabId) {
      tabStore.closeTab(tabStore.activeTabId)
    }
  }
  
  // Ctrl/Cmd + Shift + T: 恢复最近关闭的标签页
  if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'T') {
    event.preventDefault()
    // TODO: 实现恢复标签页功能
  }
  
  // F5: 刷新当前连接
  if (event.key === 'F5') {
    event.preventDefault()
    if (connectionStore.activeConnectionId) {
      connectionStore.refreshConnectionStatus(connectionStore.activeConnectionId)
    }
  }
  
  // Ctrl/Cmd + R: 执行查询
  if ((event.ctrlKey || event.metaKey) && event.key === 'r') {
    event.preventDefault()
    // TODO: 触发当前标签页的查询执行
  }
  
  // Esc: 取消当前操作
  if (event.key === 'Escape') {
    // TODO: 取消当前正在执行的查询
  }
}
</script>

<style scoped>
.main-layout {
  font-family: 'Inter', sans-serif;
}

.top-bar {
  height: 48px;
  border-bottom: 1px solid #e5e7eb;
  background: #ffffff;
  z-index: 100;
}

.main-content {
  min-height: 0; /* 重要：允许flex子元素收缩 */
}

.content-wrapper {
  background: #f9fafb;
  min-width: 0; /* 重要：允许flex子元素收缩 */
}

.status-bar {
  height: 24px;
  background: #f3f4f6;
  border-top: 1px solid #e5e7eb;
  z-index: 100;
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 消息提示 */
.message-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 9998;
  max-width: 400px;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #3b82f6;
}

.message-success {
  border-left-color: #10b981;
}

.message-warning {
  border-left-color: #f59e0b;
}

.message-error {
  border-left-color: #ef4444;
}

.message-icon {
  margin-right: 8px;
  font-size: 16px;
}

.message-text {
  flex: 1;
  font-size: 14px;
  color: #374151;
}

.message-close {
  margin-left: 8px;
  color: #9ca3af;
}

/* 消息动画 */
.message-enter-active,
.message-leave-active {
  transition: all 0.3s ease;
}

.message-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.message-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100% !important;
    height: auto;
    order: 2;
  }
  
  .content-wrapper {
    order: 1;
  }
  
  .message-container {
    left: 20px;
    right: 20px;
    max-width: none;
  }
}
</style> 